package cn.sll.org.controller;

import cn.sll.base.annotation.PreAuthorize;
import cn.sll.base.jwt.UserInfo;
import cn.sll.base.util.AjaxResult;
import cn.sll.base.util.LoginContext;
import cn.sll.base.util.PageList;
import cn.sll.org.domain.Department;
import cn.sll.org.query.DepartmentQuery;
import cn.sll.org.service.impl.DepartmentServiceImpl;
import cn.sll.user.domain.Logininfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/dept")
public class DepartmentController {

    @Autowired
    private DepartmentServiceImpl departmentService;

    @GetMapping
    public List<Department> list(){
        return departmentService.findAll();
    }

    @GetMapping("/{id}")
    public Department findById(@PathVariable("id") Long id){
        return departmentService.findById(id);
    }

    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Department department){

            if (department.getId()!=null){
                departmentService.update(department);
            }else {
                departmentService.add(department);
            }

            return  AjaxResult.me().success();

    }

    @DeleteMapping("/{id}")
    public AjaxResult deleteById(@PathVariable("id") Long id) {
        departmentService.delete(id);
        return  AjaxResult.me().success();
    }

    @PostMapping
    public PageList<Department> queryByPage(@RequestBody DepartmentQuery query, HttpServletRequest request) {
        Logininfo logininfo = LoginContext.getLogininfo(request);
        System.out.println(logininfo);
        return departmentService.queryByPage(query);
    }

    @PatchMapping()
    @PreAuthorize(name = "批量删除部门",sn = "department:batchDel")
    public AjaxResult batchDelete(@RequestBody List<Long> ids){
        departmentService.batchDelete(ids);
        return AjaxResult.me().success();
    }

    @GetMapping("/tree")
    @PreAuthorize(name = "查询部门级数",sn = "department:tree")
    public List<Department> tree() {
        return departmentService.tree();
    }

}
